﻿using System.Collections.Generic;
using System.Web.Http;
using DefaultConnection;
using MementoWeb.Models;
using AutoMapper;
using System.Linq;
using MementoLibrary.DTOs;
using System.Data.SqlClient;
using System.Net;
using System.Net.Http;

namespace MementoWeb.Controllers
{
    public class CategoryGroupController : ApiController
    {
        private readonly IDataRepository _dataRepository;

        public CategoryGroupController( IDataRepository dataRepository )
        {
            _dataRepository = dataRepository;
        }

        public IEnumerable<CategoryGroupDTO> Get()
        {
            try
            {
                var categoryGroups = _dataRepository.GetAllCategoryGroups();
                var categories = _dataRepository.GetAllCategories();
                var categoryGroupsWithCategories = Mapper.Map<IEnumerable<CategoryGroupDTO>>(categoryGroups);
                foreach (var categoryGroup in categoryGroupsWithCategories)
                {
                    categoryGroup.Categories = Mapper.Map<IEnumerable<CategoryDTO>>(categories.Where(c => c.CategoryGroupId == categoryGroup.CategoryGroupId).ToList());
                }
                return categoryGroupsWithCategories;
            }
            catch (SqlException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }

        public CategoryGroup GetById( int id )
        {
            return _dataRepository.GetCategoryGroupById(id);
        }

        public void CreateNew( CategoryGroup workCategory )
        {
            _dataRepository.CreateNewCategoryGroup(workCategory);
        }

        public void Update( CategoryGroup workCategory )
        {
            _dataRepository.SaveCategoryGroupChanges(workCategory);
        }

        public void Delete( int id )
        {
            _dataRepository.DeleteCategoryGroup(id);
        }
    }
}
